from fastapi import HTTPException
from starlette.responses import JSONResponse
from models.course import Course

async def query_all_course(week_day: int = None, time: int = None, name: str = None, teacher: str = None, place: str = None) -> list[Course]:
    query = Course.filter()

    if week_day is not None:
        query = query.filter(week_day=week_day)
    
    if time is not None:
        query = query.filter(time=time)

    if name:
        query = query.filter(name=name)
    
    if teacher:
        query = query.filter(teacher=teacher)

    if place:
        query = query.filter(place=place)

    courses = await query
    if not courses:
        raise HTTPException(status_code=403, detail="未找到匹配课程")
    return courses

async def add_course(week_day: int, time: int,name: str, teacher: str, place: str) -> Course:
    
    course = await Course.create(
        week_day=week_day,
        time=time,
        name=name,
        teacher=teacher,
        place=place
    )
    if course:
        return {"msg": "创建课程成功"}
    else:
        return {"msg": "创建课程失败"}

async def delete_course_by_id(course_id: int) -> Course:
    course = await Course.get_or_none(id=course_id)
    if course:
        await course.delete()
        return {"msg": "删除课程成功"}
    else:
        return {"msg": "删除课程失败"}

async def update_course_by_id(id: int, name: str, week_day: int, time: int, teacher: str, place: str) -> Course:
    course = await Course.get_or_none(id=id)
    if not course:
        raise HTTPException(status_code=403, detail="未找到匹配课程")
    
    await course.update_from_dict({
        "id": id,
        "week_day": week_day,
        "time": time,
        "name": name,
        "teacher": teacher,
        "place": place
    })
    await course.save()
    return JSONResponse(content={"msg": "更新课程成功"}, status_code=200)